package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        if (CollectionUtils.isEmpty(params)) {
            return null;
        }

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())
                .or()
                .eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());


        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        List<Long> items = mergeVo.getItems();
        if (CollectionUtils.isEmpty(items)) {
            return;
        }

        // 如果采购单id为空，则新建一个采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);

            // 写入采购单id
            purchaseId = purchaseEntity.getId();
        }

        // TODO 确认采购单状态为 0/1，才可以合并

        // 准备采购单明细数据
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntityList = items.stream().map(detailId -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(detailId);
            detailEntity.setPurchaseId(finalPurchaseId);
            // 已分配：表示已分配给采购单
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        // 批量更新采购单明细
        purchaseDetailService.updateBatchById(detailEntityList);

        // 再次更新采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }



    @Transactional
    @Override
    public void received(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        // 1、过滤状态为 新建/已分配 的采购单数据，只有这些数据才可以被领取
        List<PurchaseEntity> rightPurchaseEntitiyList;
        List<PurchaseEntity> purchaseEntitiyList = (List<PurchaseEntity>) this.listByIds(ids);
        if (CollectionUtils.isEmpty(purchaseEntitiyList)) {
            return;
        }
        rightPurchaseEntitiyList = purchaseEntitiyList.stream()
                .filter(entity -> WareConstant.PurchaseStatusEnum.CREATED.getCode() == entity.getStatus() || WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() == entity.getStatus())
                .collect(Collectors.toList());

        // 2、改变采购单的状态为：已领取
        rightPurchaseEntitiyList.forEach(purchase -> {
            purchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchase.setUpdateTime(new Date());
        });
        this.updateBatchById(rightPurchaseEntitiyList);

        // 3、改变采购项的状态为：正在采购
        List<Long> purchaseIdList = rightPurchaseEntitiyList.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
        // 根据采购单id批量查询采购项
        List<PurchaseDetailEntity> updateDetailEntityList;
        List<PurchaseDetailEntity> detailEntityList = purchaseDetailService.listDetailByPurchaseIdList(purchaseIdList);
        if (!CollectionUtils.isEmpty(detailEntityList)) {
            updateDetailEntityList = detailEntityList.stream().map(detail -> {
                PurchaseDetailEntity updateDetail = new PurchaseDetailEntity();
                updateDetail.setId(detail.getId());
                updateDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return updateDetail;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(updateDetailEntityList);
        }

    }


    @Transactional
    @Override
    public void done(PurchaseDoneVo vo) {
        Long id = vo.getId();

        // 更新采购项
        boolean purchaseSuccessFlag = true;
        List<PurchaseDetailEntity> updateDetailList = new ArrayList<>();
        List<PurchaseItemDoneVo> items = vo.getItems();
        if (!CollectionUtils.isEmpty(items)) {
            for (PurchaseItemDoneVo item : items) {
                PurchaseDetailEntity updateDetail = new PurchaseDetailEntity();
                updateDetail.setId(item.getItemId());
                updateDetail.setStatus(item.getStatus());
                updateDetailList.add(updateDetail);

                if (WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode() == item.getStatus()) {
                    purchaseSuccessFlag = false;
                } else {
                    // 将成功采购的进行入库
                    PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                    wareSkuService.addStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());
                }
            }
        }
        purchaseDetailService.updateBatchById(updateDetailList);

        // 更新采购单
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(purchaseSuccessFlag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}













































